package com.jfunit.java.util;

import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Web 操作工具类
 * @author Administrator
 *
 */
public final class WebUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebUtil.class);

    /**
     * 重定向请求
     */
    public static void redirectRequest(String path, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.sendRedirect(request.getContextPath() + path);
        } catch (Exception e) {
            LOGGER.error("重定向请求出错！", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 从请求中获取所有参数（当参数名重复时，用后者覆盖前者）
     */
    public static Map<String, Object> getRequestParamMap(HttpServletRequest request) {
        Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
        
        try {
            String method = request.getMethod();
            if (method.equalsIgnoreCase("put") || method.equalsIgnoreCase("delete")) {
                String body = CodeUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
                if (StringUtils.isNoneEmpty(body)) {
                    String[] params = StringUtils.split(body, "&");
                    if (ArrayUtils.isNotEmpty(params)) {
                        for (String param : params) {
                            String[] array = StringUtils.split(param, "=");
                            if (ArrayUtils.isNotEmpty(array) && array.length == 2) {
                                String paramName = array[0];
                                String paramValue = array[1];
                                if (checkParamName(paramName)) {
                                    if (paramMap.containsKey(paramName)) {
                                        paramValue = paramMap.get(paramName) + StringUtil.SEPARATOR + paramValue;
                                    }
                                    paramMap.put(paramName, paramValue);
                                }
                            }
                        }
                    }
                }  
            }else{
                Enumeration<String> paramNames = request.getParameterNames();
                while(paramNames.hasMoreElements()){
                    String paramName = paramNames.nextElement();
                    if (checkParamName(paramName)) {
                        String[] paramValues = request.getParameterValues(paramName);
                        if (ArrayUtils.isNotEmpty(paramValues)) {
                            if (paramValues.length == 1) {
                                paramMap.put(paramName, paramValues[0]);
                            }else{
                                StringBuilder paramValue = new StringBuilder("");
                                for (int i = 0; i < paramValues.length; i++) {
                                    paramValue.append(paramValues[i]);
                                    if (i!= paramValues.length-1) {
                                        paramValue.append(StringUtil.SEPARATOR);
                                    }
                                }                                
                                paramMap.put(paramName, paramValue.toString());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("获取请求参数出错！", e);
            throw new RuntimeException(e);
        }
        return paramMap;
    }

    private static boolean checkParamName(String paramName) {
        //忽略 jQuery 缓存参数
        return !paramName.equals("_");
    }
    
    /**
     * 发送错误代码
     */
    public static void sendError(int code, String message, HttpServletResponse response) {
        try {
            response.sendError(code, message);
        } catch (Exception e) {
            LOGGER.error("发送错误代码出错！", e);
            throw new RuntimeException(e);
        }
    }
}
